<template>
    <div class="zh-quality-setting">
        <nav-header></nav-header>

        <div class="setting-wrapper" v-loading="loading.status" :element-loading-text="loading.txt">
            <p class="setting-title">角色设权重</p>
            <div class="setting-box">
                <div>
                    <span>角色</span><span>权重</span>
                </div>
                <div>
                    <span>教师评委</span><span>{{(listData.teacher_weight * 100).toFixed()}}%</span>
                </div>
                <div>
                    <span>学生评委</span><span>{{(listData.student_weight * 100).toFixed()}}%</span>
                </div>
                <div>
                    <span>自评</span><span>{{(listData.my_weigth * 100).toFixed()}}%</span>
                </div>
            </div>
            <span class="setting-edit" @click="editWeights">编辑</span>

            <p class="setting-title">分段标准</p>
            <div class="subsection-box">
                <span 
                    v-for="(item, inx) in subsection" 
                    :key="inx" 
                    :title="item.title"
                    :style="{'width': setWidth(item, inx), 'background': colorList[inx]}">
                    <i class="zero" v-if="inx === 0">0%</i>{{item.title}}
                    <i :class="setPostiotn(item, inx) ? 'top-text' : ''">{{(item.content * 100).toFixed() + '%'}}</i></span>
            </div>
            <span class="setting-edit" style="margin-top: 48px;" @click="editSubsection">编辑</span>
        </div>

        <el-dialog 
            title="编辑角色权重" 
            :visible.sync="weightsVisible" 
            class="edit-weights" 
            width="400px" 
            :close-on-click-modal="false">
            <el-form :model="weightsForm" :rules="rules" ref="weightsForm" label-width="100px">
                <el-form-item label="教师评委：" prop="teacherWeight">
                    <el-input-number 
                        class="input-number-text"
                        v-model="weightsForm.teacherWeight" 
                        controls-position="right" 
                        :min="0" 
                        :max="100"
                        :precision="0">
                    </el-input-number>%
                </el-form-item>
                <el-form-item label="学生评委：" prop="studentWeight">
                    <el-input-number 
                        class="input-number-text"
                        v-model="weightsForm.studentWeight" 
                        controls-position="right" 
                        :min="0" 
                        :max="100"
                        :precision="0">
                    </el-input-number>%
                </el-form-item>
                <el-form-item label="自评：" prop="myWeigth">
                    <el-input-number 
                        class="input-number-text"
                        v-model="weightsForm.myWeigth" 
                        controls-position="right" 
                        :min="0" 
                        :max="100"
                        :precision="0">
                    </el-input-number>%
                </el-form-item>

                <span class="tips-text">注：权重相加必须等于100%</span>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitWeights('weightsForm')">保存</el-button>
            </div>
        </el-dialog>

        <el-dialog 
            title="编辑分段标准" 
            :visible.sync="subsectionVisible" 
            class="edit-weights" 
            width="800px" 
            :close-on-click-modal="false">
            <div class="subsection-box subsection-weights">
                <span 
                    v-for="(item, inx) in tempSubsection" 
                    :key="inx" 
                    :title="item.title"
                    :style="{'width': setWidth2(item, inx), 'background': colorList[inx]}">
                    <i class="zero" v-if="inx === 0">0%</i>{{item.title}}
                    <div 
                        class="subsection-img" v-if="inx !== tempSubsection.length -1" 
                        :class="setPostiotn3(item, inx) ? 'bottom-img' : ''"
                        @mousedown="mouseDown($event, inx)">
                        <img src="./../../../../static/image/affairs/quality/roll.png" alt="滑块">
                    </div>
                    <i :class="setPostiotn2(item, inx) ? 'top-text' : ''">{{(item.content * 100).toFixed() + '%'}}</i></span>
            </div>

            <div class="setting-box setting-weights">
                <div>
                    <span>分段名称</span><span>分段区间</span><span>操作</span>
                </div>
                <div v-for="(item, inx) in tempSubsection" :key="inx">
                    <span v-if="editSubIndex !== inx" @click="editTitleVal(item.title, inx)" class="title-hover">{{item.title}}</span>
                    <span v-else>
                        <el-input v-model="subTitle" @blur="changeSubTitle(inx)" :maxLength="10" ref="subInput"></el-input>
                    </span>
                    <span>{{inx === 0 ? (`0%-${(+item.content * 100).toFixed()}`) : `${(+tempSubsection[inx-1].content * 100).toFixed()}%-${(+item.content * 100).toFixed()}`}}%</span>
                    <span class="operate-btn">
                        <img src="./../../../../static/image/affairs/quality/group.png" @click="newSubsection(item, inx)" alt="新增分段">
                        <span @click="deleteSubsection(item, inx)">删除</span>
                    </span>
                </div>
            </div>

            <div class="tips-text">
                <span style="display: block;margin-bottom: 12px;">注：点击分段名称进行编辑</span>
                <span>注：分段区间包括包含前分值</span>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitSubsection">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export  default {
    data() {
        return {
            weightsVisible: false, // 角色权重弹窗
            subsectionVisible: false, // 分段标准弹窗
            subTitle: '', // 分段标准名称
            editSubIndex: null, // 分段标准下标
            colorList: ['#DD3D3D', '#FF9743', '#FFD367', '#8EE40A', '#00CEBF', '#2EA1FF', '#0065FB', '#4E36FF', '#9F38DF', '#DF3892'], // 分段标准默认颜色
            subsection: [], // 分段标准数据
            tempSubsection: [], // 编辑分段标准数据
            listData: { // 角色权重数据
                teacher_weight: 0,
                student_weight: 0,
                my_weigth: 0,
            },
            loading:{
                status: false,
                txt: '获取数据...',
            },
            weightsForm: { // 角色权重表单
                teacherWeight: 0,
                studentWeight: 0,
                myWeigth: 0
            },
            rules: {
                teacherWeight: [
                    { required: true, message: '请输入教师评委权重', trigger: 'blur' },
                ],
                studentWeight: [
                    { required: true, message: '请输入学生评委权重', trigger: 'blur' },
                ],
                myWeigth: [
                    { required: true, message: '请输入自评权重', trigger: 'blur' },
                ]
            }
        }
    },
    created() {
        this.getList();
        this.getSubsection();
    },
    computed: {
        /**
         * 设置分段宽度
         * @param {Object} obj 分段信息
         * @param {Number} inx 分段下标
         * 1% 转换为 10px
         */
        setWidth() {
            return function(obj, inx) {
                if (inx === 0) {
                    return +obj.content * 1000 + 'px'
                } else {
                    return (+obj.content - +this.subsection[inx-1].content) * 1000 + 'px'
                }
            }
        },
        /**
         * 设置分段宽度
         * @param {Object} obj 分段信息
         * @param {Number} inx 分段下标
         * 1% 转换为 7px
         */
        setWidth2() {
            return function(obj, inx) {
                if (inx === 0) {
                    return +obj.content * 700 + 'px'
                } else {
                    return (+obj.content - +this.tempSubsection[inx-1].content) * 700 + 'px'
                }
            }
        },
        /**
         * 分段距离小于 3% 的时候，分数放在上面
         * @param {Object} obj 分段信息
         * @param {Number} inx 分段下标
         */
        setPostiotn() {
            return function(obj, inx) {
                let score = 0;

                if (inx === 0) {
                    score = +obj.content * 100;
                } else {
                    score = (+obj.content - +this.subsection[inx-1].content) * 100;
                }

                if (score <= 3) {
                    if (inx === 0) {
                        this.subsection[inx].top = true;
                        return true;
                    } else {
                        if (this.subsection[inx-1].top) {
                            return false;
                        } else {
                            this.subsection[inx].top = true;
                            return true;
                        }
                    }
                }
                    
                return false;
            }
        },
        /**
         * 分段距离小于 5% 的时候，分数放在上面
         * @param {Object} obj 分段信息
         * @param {Number} inx 分段下标
         */
        setPostiotn2() {
            return function(obj, inx) {
                if (inx === this.tempSubsection.length -1) {
                    return false;
                }

                if (inx%2 === 1) {
                    return true;
                } else {
                    return false;
                }
            }
        },
        /**
         * 分段距离小于 5% 的时候，分数放在上面
         * @param {Object} obj 分段信息
         * @param {Number} inx 分段下标
         */
        setPostiotn3() {
            return function(obj, inx) {
                if (inx%2 === 1) {
                    return true;
                } else {
                    return false;
                }
            }
        },
    },
    methods: {
        /**
         * 移动滑块
         * @param {Object} event 当前点击对象
         * @param {Number} inx 数组下标
         */
        mouseDown(event, inx) {
            let temp = this.tempSubsection;
            let dom = event.currentTarget;
            let disX = event.clientX - dom.offsetLeft; // 鼠标按下，计算当前元素距离可视区的距离
            let _content = +temp[inx].content * 100;

            document.onmousemove = function(e) {
                let score1 = 0; // 左边分数
                let score2 = +temp[inx].content * 100; // 中间分数
                let score3 = 0; // 右边分数
                let lX = e.clientX - disX; // 通过事件委托，计算移动的距离
                let len = event.clientX - e.clientX;
                let num = Math.floor(Math.abs(len) / 7);

                if (inx === 0) {
                    score3 = +temp[inx+1].content * 100 - 1;

                    if (len > 0) {
                        if (score2 > 1) {
                            temp[inx].content = ((_content - num) / 100).toFixed(2);
                        } else {
                            temp[inx].content = '0.01';
                        }
                    } else if (len < 0) {
                        if (score2 < score3) {
                            temp[inx].content = ((_content + num) / 100).toFixed(2);
                        } else {
                            temp[inx].content = (score3 / 100).toFixed(2);
                        }
                    }
                } else if (temp.length > 2 && inx === temp.length - 2) {
                    score1 = +temp[inx-1].content * 100 + 1;

                    if (len > 0) {
                        if (score2 > score1) {
                            temp[inx].content = ((_content - num) / 100).toFixed(2);
                        } else {
                            temp[inx].content = (score1 / 100).toFixed(2);
                        }
                    } else if (len < 0) {
                        if (score2 < 99) {
                            temp[inx].content = ((_content + num) / 100).toFixed(2);
                        } else {
                            temp[inx].content = '0.99';
                        }
                    }
                } else {
                    score1 = +temp[inx-1].content * 100 + 1;
                    score3 = +temp[inx+1].content * 100 - 1;

                    if (len > 0) {
                        if (score2 > score1) {
                            temp[inx].content = ((_content - num) / 100).toFixed(2);
                        } else {
                            temp[inx].content = (score1 / 100).toFixed(2);
                        }
                    } else if (len < 0) {
                        if (score2 < score3) {
                            temp[inx].content = ((_content + num) / 100).toFixed(2);
                        } else {
                            temp[inx].content = (score3 / 100).toFixed(2);
                        }
                    }
                }
            }

            document.onmouseup = function(e) {
                document.onmousemove = null;
                document.onmouseup = null;
            };

            event.preventDefault(); // 滑块为图片，阻止图片在浏览器的默认行为
            // return false; // 不加的话可能导致黏连，就是拖到一个地方时div粘在鼠标上不下来，相当于onmouseup失效
        },
        /**
         * 获取素质评价
         */
        getList() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;
                this.listData = deep_clone(res.data);
            });

            this.$ajax.get('api/quality/quality_weight', {func: {success: success}})
        },
        /**
         * 获取分段标准
         */
        getSubsection() {
            this.loading.status = true;

            let success = (res => {
                this.loading.status = false;
                this.subsection = deep_clone(res.data);
            });

            this.$ajax.get('api/quality/quality_subsection', {func: {success: success}})
        },
        /**
         * 编辑角色权重
         */
        editWeights() {
            this.weightsVisible = true;
            this.weightsForm = {
                teacherWeight: this.listData.teacher_weight * 100,
                studentWeight: this.listData.student_weight * 100,
                myWeigth: this.listData.my_weigth * 100
            }
        },
        /**
         * 保存角色权重
         */
        submitWeights(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (+this.weightsForm.teacherWeight + +this.weightsForm.studentWeight + +this.weightsForm.myWeigth !== 100) {
                        this.$message.warning('权重相加不等于100%');

                        return false;
                    }

                    this.loading.status = true;
                    let quality_weight = [];

                    quality_weight['teacher_weight'] =  this.weightsForm.teacherWeight / 100;
                    quality_weight['student_weight'] =  this.weightsForm.studentWeight / 100;
                    quality_weight['my_weigth'] =  this.weightsForm.myWeigth / 100;

                    let success = (res => {
                        this.loading.status = false;
                        this.weightsVisible = false;
                        this.$message.success(res.msg);

                        this.getList();
                    });
                    const fail = (res => {
                        this.loading.status = false;
                        this.$message.error(res.msg);
                    })
                    const params = {
                        quality_weight
                    }

                    this.$ajax.put('api/quality/quality_weight', params, {func: {success: success, fail: fail}})
                } else {
                    return false;
                }
            });
        },
        /**
         * 显示分段名称编辑框
         * @param {String} name 分段名称
         * @param {Number} inx 下标
         */
        editTitleVal(name, inx) {
            this.editSubIndex = inx;
            this.subTitle = name;
            this.$nextTick(() => {
                this.$refs['subInput'][0].focus();
            })
        },
        /**
         * 隐藏分段名称
         * @param {Number} inx 下标
         */
        changeSubTitle(inx) {
            this.editSubIndex = null;
            this.tempSubsection[inx].title = this.subTitle;
        },
        /**
         * 新增分段
         * @param {Object} obj 当前分段信息
         * @param {Number} inx 下标
         */
        newSubsection(obj, inx) {
            if (this.tempSubsection.length > 9) {
                this.$message.warning('分段标准最多为10个');
                return false;
            }

            let number = inx === 0 ? obj.content : (obj.content - this.tempSubsection[inx-1].content);
            number = number.toFixed(2);

            if (number > 0.05) {
                let number2 = this.tempSubsection[inx].content;
                let temp = {
                    title: '新增分段',
                    content: number2
                }

                this.tempSubsection[inx].content = +(number2 - 0.05).toFixed(2);
                this.tempSubsection.splice(inx+1, 0, temp)
            } else {
                this.$message.warning('新增分段标准默认值为5%，当前分段区间小于5%');
            }
        },
        /**
         * 删除分段
         * @param {Object} obj 当前分段信息
         * @param {Number} inx 下标
         */
        deleteSubsection(obj, inx) {
            if (this.tempSubsection.length > 2) {
                if (inx !== 0) {
                    let content = obj.content;
                    this.tempSubsection.splice(inx, 1);
                    this.tempSubsection[inx-1].content = content;
                } else {
                    this.tempSubsection.splice(inx, 1);
                }
            } else {
                this.$message.warning('分段标准长度不可以小于2');
            }
        },
        /**
         * 编辑分段标准
         */
        editSubsection() {
            this.subsectionVisible = true;
            this.tempSubsection = deep_clone(this.subsection);

        },
        /**
         * 保存分段标准
         */
        submitSubsection(formName) {
            this.loading.status = true;
            let quality_subsection = [];

            this.tempSubsection.forEach(item => {
                quality_subsection.push({
                    title: item.title,
                    content: item.content
                })
            })

            let success = (res => {
                this.loading.status = false;
                this.subsectionVisible = false;
                this.$message.success(res.msg);

                this.getSubsection();
            });
            const fail = (res => {
                this.loading.status = false;
                this.$message.error(res.msg);
            })
            const params = {
                quality_subsection
            }

            this.$ajax.put('api/quality/quality_subsection', params, {func: {success: success, fail: fail}})
        },
    },
}
</script>

<style lang="scss">
.zh-quality-setting {
    .setting-wrapper {
        .setting-title:before {
            content: '';
            display: inline-block;
            margin-right: 8px;
            width: 6px;
            height: 18px;
            vertical-align: middle;
            background: #348EFC;
        }

        .setting-title {
            margin-bottom: 20px;
        }

        .setting-edit {
            display: inline-block;
            margin-top: 20px;
            margin-bottom: 26px;
            padding: 6px 26px;
            color: #FFFFFF;
            background: #348EFC;
            border-radius: 2px;
            cursor: pointer;
        }
    }

    .subsection-box {
        margin-top: 45px;
        width: 1000px;
        background: #F2F2F2;

        span {
            position: relative;
            display: inline-block;
            height: 28px;
            line-height: 28px;
            font-size: 12px;
            color: #FFFFFF;
            text-align: center;
            vertical-align: top;
            box-sizing: border-box;

            i {
                position: absolute;
                bottom: -24px;
                color: #666;
                font-style: normal;
                z-index: 2;
                width: 34px;
            }

            i:not(.zero) {
                right: 0;
                transform: translate(50%);
            }

            .zero {
                left: 0;
                transform: translate(-50%);
            }

            .top-text {
                top: -24px;
            }
        }
    }

    .subsection-weights {
        position: relative;
        margin-bottom: 76px;
        width: 700px;
        user-select:none;

        span:first-child:before,
        span:last-child:before {
            content: '';
            position: absolute;
            top: -24px;
            display: inline-block;
            width: 1px;
            height: 20px;
            background: #C5C5C5;
        }

        span:first-child:before {
            left: 0;
        }

        span:last-child:before {
            right: 0;
        }

        span:last-child {
            i {
                right: -10px;
            }
        }

        .subsection-img {
            position: absolute;
            top: -42px;
            right: 0;
            width: 22px;
            transform: translate(50%);
        }

        // .subsection-img:hover {
        //     cursor: col-resize;
        // }

        .subsection-img::before {
            content: '';
            position: absolute;
            top: 22px;
            left: 11px;
            display: inline-block;
            width: 1px;
            height: 12px;
            background: #C5C5C5;
        }

        .bottom-img {
            top: initial;
            bottom: -52px;
        }

        .bottom-img::before {
            top: initial;
            bottom: 32px;
        }
    }

    .setting-box {
        width: 403px;
        border: 1px solid #DDDDDD;
        box-sizing: border-box;

        >div {
            height: 36px;
            line-height: 36px;
            font-size: 0;

            >span {
                display: inline-block;
                width: 200px;
                text-align: center;
                font-size: 14px;
                color: #000;
            }

            >span:not(:last-child) {
                border-right: 1px solid #DDDDDD;
            }
        }

        >div:not(:last-child) {
            border-bottom: 1px solid #DDDDDD;
        }

        >div:first-child {
            background: #F2F2F2;
        }
    }

    .setting-weights {
        margin-bottom: 26px;
        width: 604px;

        .operate-btn {
            img {
                margin-right: 40px;
                cursor: pointer;
            }

            span {
                color: #f56c6c;
                cursor: pointer;
            }
        }

        .title-hover:hover {
            color: #348EFC;
        }
    }

    .edit-weights {
        .input-number-text {
            margin-right: 10px;
            width: 70px;

            >span {
                display: none;
            }

            input {
                text-align: center;
            }

            .el-input__inner {
                padding: 0;
            }
        }

        .el-form-item__label {
            color: #000;
        }
    }

    .tips-text {
        display: inline-block;
        margin-top: 14px;
        margin-bottom: 28px;
        font-size: 12px;
        color: #666666;
    }
}
</style>